package com.ztewatch.wearcontacts;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.ContentUris;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.CallLog.Calls;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.Groups;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;

import com.ztewatch.wearcontacts.loader.SortContactsAndGroupLoader;
import com.ztewatch.wearcontacts.presenter.LoadCallLogDataPresenter;
import com.ztewatch.wearcontacts.presenter.LoadCursorDataPresenter;
import com.ztewatch.wearcontacts.utils.CallUtil;
import com.ztewatch.wearcontacts.utils.ContactQuery;
import com.ztewatch.wearcontacts.view.BaseGridViewAdapter;
import com.ztewatch.wearcontacts.view.ContactVoicecallCursorAdapter;
import com.ztewatch.wearcontacts.view.ILoadCallLogDataView;
import com.ztewatch.wearcontacts.view.ILoadCursorDataView;
import com.ztewatch.wearcontacts.view.ScrollGridView;

public class WearContactVoiceCallMainActivity extends Activity implements
		ILoadCursorDataView, ILoadCallLogDataView {
	private ScrollGridView base_gridview;
	public static final String VOICE_CALL_FLAG = "voice_call_flag";
	private List<HashMap<String, Object>> baseDataList = new ArrayList<HashMap<String, Object>>();

	private ScrollGridView contact_gridview;
	private ContactVoicecallCursorAdapter contactCursorAdapter;
	private Uri mCurLookupUri;
	private LoadCursorDataPresenter mLoadCursorDataPresenter;
	private LoadCallLogDataPresenter mLoadCallLogDataPresenter;

	// private static final String SORT_KEY_ORDER = Contacts.PINNED
	// + " COLLATE NOCASE ASC";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_wear_contact_main);
		initBaseGridView();
		initContactGridView();
		initContentObserver();
		mLoadCursorDataPresenter = new LoadCursorDataPresenter(this, this,
				contactCursorAdapter);
		mLoadCallLogDataPresenter = new LoadCallLogDataPresenter(this, this);
	}

	private void initContentObserver() {
		getContentResolver().registerContentObserver(Calls.CONTENT_URI, true,
				new CallLogObserver(new Handler()));
	}

	private final class CallLogObserver extends ContentObserver {

		public CallLogObserver(Handler handler) {
			super(handler);
		}

		@Override
		public void onChange(boolean selfChange) {
			super.onChange(selfChange);
			mLoadCallLogDataPresenter.restartLoader(2);
		}
	}

	private void initContactGridView() {
		contact_gridview = (ScrollGridView) findViewById(R.id.contact_gridview);
		contactCursorAdapter = new ContactVoicecallCursorAdapter(this, null);
		contact_gridview.setAdapter(contactCursorAdapter);
		contact_gridview.setOnItemClickListener(new ContactItemClickListener());
	}

	private void initBaseGridView() {
		base_gridview = (ScrollGridView) findViewById(R.id.base_gridview);
		HashMap<String, Object> itemHashMap = new HashMap<String, Object>();
		itemHashMap.put(BaseGridViewAdapter.ITEM_IMAGE,
				R.drawable.ic_add_contact);
		itemHashMap.put(BaseGridViewAdapter.ITEM_TEXT, getResources()
				.getString(R.string.base_newcontact));
		baseDataList.add(itemHashMap);

		HashMap<String, Object> itemHashMap1 = new HashMap<String, Object>();
		itemHashMap1.put(BaseGridViewAdapter.ITEM_IMAGE, R.drawable.ic_edit);
		itemHashMap1.put(BaseGridViewAdapter.ITEM_TEXT, getResources()
				.getString(R.string.base_edit));
		baseDataList.add(itemHashMap1);

		HashMap<String, Object> itemHashMap2 = new HashMap<String, Object>();
		itemHashMap2.put(BaseGridViewAdapter.ITEM_IMAGE, R.drawable.ic_sort);
		itemHashMap2.put(BaseGridViewAdapter.ITEM_TEXT, getResources()
				.getString(R.string.base_Sort));
		baseDataList.add(itemHashMap2);

		HashMap<String, Object> itemHashMap3 = new HashMap<String, Object>();
		itemHashMap3.put(BaseGridViewAdapter.ITEM_IMAGE, R.drawable.ic_folder);
		itemHashMap3.put(BaseGridViewAdapter.ITEM_TEXT, getResources()
				.getString(R.string.base_Folder));
		baseDataList.add(itemHashMap3);
		BaseGridViewAdapter baseGridViewAdapter = new BaseGridViewAdapter(this,
				baseDataList);
		base_gridview.setAdapter(baseGridViewAdapter);
		base_gridview.setOnItemClickListener(new BaseItemClickListener());
	}

	private class ContactItemClickListener implements OnItemClickListener {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			if (position == 0) {// History
				Intent intent = new Intent();
				intent.setClass(WearContactVoiceCallMainActivity.this,
						WearContactCallLogActivity.class);
				startActivity(intent);
				return;
			}
			Cursor cursor = (Cursor) contactCursorAdapter.getItem(position);
			if (cursor != null) {
				int is_group_index = cursor
						.getColumnIndex(SortContactsAndGroupLoader.IS_GROUP);
				if (is_group_index != -1) {
					int is_group = cursor.getInt(is_group_index);
					if (is_group == 0) {
						mCurLookupUri = getContactUri(cursor);
						if (mCurLookupUri != null) {// contact
							getLoaderManager().initLoader(1, null,
									VoicecallloaderCallbacks);
						}
					} else {
						int groupId_index = cursor.getColumnIndex(Groups._ID);
						if (groupId_index != -1) {
							long groupId = cursor.getLong(groupId_index);
							Uri group_uri = getGroupUriFromId(groupId);
							Intent intent = new Intent(
									WearContactVoiceCallMainActivity.this,
									WearContactGroupDetailActivity.class);
							int title_index = cursor
									.getColumnIndex(Contacts.DISPLAY_NAME_PRIMARY);// Groups.TITLE
							if (title_index != -1) {
								String title = cursor.getString(title_index);
								intent.putExtra(
										WearContactGroupListActivity.GROUP_TITLE,
										title);
							}
							intent.putExtra(VOICE_CALL_FLAG, true);
							intent.setData(group_uri);
							startActivity(intent);
						}
					}
				} else {
					Uri contactUri = getContactUri(cursor);
					if (contactUri != null) {// contact
						Intent intent = new Intent(
								WearContactVoiceCallMainActivity.this,
								WearContactDisplayActivity.class);
						intent.setData(contactUri);
						startActivity(intent);
					}
				}
			}
		}

	}

	private class BaseItemClickListener implements OnItemClickListener {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			switch (position) {
			case 0:// new contact
				Intent intent = new Intent();
				intent.setAction(PasswordkeypadActivity.NEW_CONTACT_ACTION);
				intent.putExtra(VOICE_CALL_FLAG, true);
				if (getResources().getBoolean(R.bool.config_LGU_flag)) {
					intent.setClass(WearContactVoiceCallMainActivity.this,
							WearContactEditActivity.class);
				} else {
					intent.setClass(WearContactVoiceCallMainActivity.this,
							PasswordkeypadActivity.class);
				}
				startActivity(intent);
				break;
			case 1:// edit contact
				Intent intent1 = new Intent();
				intent1.setAction(PasswordkeypadActivity.EDIT_CONTACT_ACTION);
				intent1.putExtra(VOICE_CALL_FLAG, true);
				if (getResources().getBoolean(R.bool.config_LGU_flag)) {
					intent1.setClass(WearContactVoiceCallMainActivity.this,
							WearContactEditMainActivity.class);
				} else {
					intent1.setClass(WearContactVoiceCallMainActivity.this,
							PasswordkeypadActivity.class);
				}
				startActivity(intent1);
				break;
			case 2:// sort
				Intent intent2 = new Intent();
				intent2.setAction(PasswordkeypadActivity.SORT_CONTACT_ACTION);
				intent2.putExtra(VOICE_CALL_FLAG, true);
				intent2.setClass(WearContactVoiceCallMainActivity.this,
						WearContactSortActivity.class);
				startActivity(intent2);
				break;
			case 3:// folder
				Intent intent3 = new Intent();
				if (getResources().getBoolean(R.bool.config_LGU_flag)) {
					intent3.setClass(WearContactVoiceCallMainActivity.this,
							WearContactGroupListActivity.class);
				} else {
					intent3.setAction(PasswordkeypadActivity.FOLDER_CONTACT_ACTION);
					intent3.setClass(WearContactVoiceCallMainActivity.this,
							PasswordkeypadActivity.class);
				}
				startActivity(intent3);
				break;
			default:
				break;
			}
		}

	}

	public Uri getContactUri(Cursor cursor) {
		Uri uri = null;
		int id_index = cursor.getColumnIndex(Contacts._ID);
		int lookup_key_index = cursor.getColumnIndex(Contacts.LOOKUP_KEY);
		if (id_index != -1 && lookup_key_index != -1) {
			long contactId = cursor.getLong(id_index);
			String lookupKey = cursor.getString(lookup_key_index);
			uri = Contacts.getLookupUri(contactId, lookupKey);
		}
		return uri;
	}

	private Uri getGroupUriFromId(long groupId) {
		return ContentUris.withAppendedId(Groups.CONTENT_URI, groupId);
	}

	private final LoaderCallbacks<Cursor> VoicecallloaderCallbacks = new LoaderCallbacks<Cursor>() {

		@Override
		public void onLoaderReset(Loader<Cursor> arg0) {

		}

		@Override
		public void onLoadFinished(Loader<Cursor> arg0, Cursor cursor) {
			int number_type_index;
			int number_index;
			String number_type;
			String number = null;
			if (cursor != null) {
				if (!cursor.moveToFirst()) {
					cursor.close();
				} else {
					do {
						number_type_index = cursor.getColumnIndex(Data.DATA2);
						number_index = cursor.getColumnIndex(Data.DATA1);
						if (number_type_index != -1 && number_index != -1) {
							number_type = cursor.getString(number_type_index);
							if (number_type != null
									&& number_type.equals(String
											.valueOf(Phone.TYPE_MOBILE))) {
								number = cursor.getString(number_index);
								break;
							}
						}

					} while (cursor.moveToNext());
				}
			}
			if (!TextUtils.isEmpty(number)) {
				Intent intent = CallUtil.getCallIntent(number);
				startActivity(intent);
				getLoaderManager().destroyLoader(1);
			}
		}

		@Override
		public Loader<Cursor> onCreateLoader(int id, Bundle args) {
			if (mCurLookupUri != null) {
				Uri uri = Uri.withAppendedPath(mCurLookupUri,
						Contacts.Entity.CONTENT_DIRECTORY);
				return new CursorLoader(WearContactVoiceCallMainActivity.this,
						uri, ContactQuery.VOICECALL_COLUMNS, null, null,
						Contacts.Entity.RAW_CONTACT_ID);
			} else {
				return null;
			}

		}
	};

	@Override
	protected void onStart() {
		super.onStart();
		mLoadCursorDataPresenter.restartLoader(0);
		mLoadCallLogDataPresenter.restartLoader(2);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		mLoadCursorDataPresenter.destroyLoader(0);
		mLoadCallLogDataPresenter.destroyLoader(2);
	}

	@Override
	public void getLoadFinishCursor(Cursor c) {
		contactCursorAdapter.swapCursor(c);
		mLoadCursorDataPresenter.updateSort(c);
	}

	@Override
	public void getCallLogLoadFinishCursor(Cursor c) {
		if (c != null) {
			int count = c.getCount();
			if (count >= 0) {
				contactCursorAdapter.setNoReadCallLogNum(count);
				contactCursorAdapter.notifyDataSetChanged();
			}
		}
	}
}
